package com.example.onlinemusic.controller;

import com.example.onlinemusic.constant.Constant;
import com.example.onlinemusic.mapper.LoveMusicMapper;
import com.example.onlinemusic.mapper.MusicMapper;
import com.example.onlinemusic.model.Music;
import com.example.onlinemusic.model.Result;
import com.example.onlinemusic.model.User;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.BindingException;
import org.apache.tomcat.util.bcel.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/music")
public class MusicController {
    //我们要选定一个路径来存放音乐
    //在yml配置,再取出
    @Autowired
    private MusicMapper musicMapper;
    @Autowired
    private LoveMusicMapper loveMusicMapper;


    @Value("${music.local.path}")
    private String SAVE_PATH;
    // D:/music

    @RequestMapping("/upload")
    private Result addMusic(String singer, MultipartFile file, HttpSession session , HttpServletResponse response) throws IOException {

        //TODO 校验文件是否真的是音乐 MP3文件

        //TODO 再去验证是否有一模一样的存在

        //TODO 判空
        //拿全名
        String fileNameAndType = file.getOriginalFilename();
        System.out.println("fileNameAndType = " + fileNameAndType);
        String path = SAVE_PATH + "\\" + fileNameAndType;

        //判断这个路径是否有路径,没有则创建一下
        //上传服务器
        File dest = new File(path);
        log.info("dest = " + dest);
        if(!dest.exists()){
            dest.mkdir();
        }
        try {
            file.transferTo(dest);//上传文件到我们选择的路径
            log.info("服务器上传音乐成功!");
        } catch (IOException e) {
            log.info("服务器上传音乐失败!");
            throw new RuntimeException(e);
        }
        //数据库上传
        // 1. 数据准备
        Music music =  new Music();
        //取时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String time = simpleDateFormat.format(new Date());
        music.setTime(time);
        //设置url中的内容 我们暂时决定为 127.0.0.1:8080/  music/get?path=完整
        String url =  "music/get?path="+fileNameAndType;
        music.setUrl(url);
        music.setSinger(singer);
        //找到.mp3位置
        int index = fileNameAndType.lastIndexOf(".");
        String title =fileNameAndType.substring(0,index);
        music.setTitle(title);

        int ret = 0;
        try{
            User user = (User) session.getAttribute(Constant.LOGINUSER_SESSION_KEY);
            music.setUserId(user.getId());
            ret = musicMapper.addMusic(music);
        }catch (RuntimeException e) {
            System.out.println(e);
            log.info("音乐上传数据库出现异常");
            //删除服务器的音乐数据  把路径直接抹除
            dest.delete();
            return new Result(-1,"音乐上传失败",false);
        }
        //log.info("ret = " + ret);
        if(ret==0){
            log.info("音乐上传数据库失败 ret = " +  ret);
            //删除服务器的音乐数据  把路径直接抹除
            dest.delete();
            return new Result(-1,"音乐上传失败",false);
        }else {
            log.info("音乐上传数据库成功");
            response.sendRedirect("/list.html");
            return new Result(200,"音乐上传成功",true);
        }
    }

    @RequestMapping(value = "/get")
    public ResponseEntity<byte[]> get(String path){
        File file = new File(SAVE_PATH+"\\"+ path);
        byte[] bytes = null;
        try {
            bytes = Files.readAllBytes(file.toPath());
            if(bytes==null){
                log.info("找不到路径上的文件!");
                return ResponseEntity.badRequest().build();
            }
            return ResponseEntity.ok(bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // return ResponseEntity.ok(a);
        //return new ResponseEntity<>(a,HttpStatus.OK);
    }
    @RequestMapping("/delete")
    public Result deleteMusic(Integer id){
        //判断是否存在

        //查询音乐的url,拿到文件的路径
        //删服务器
        Music music = musicMapper.selectById(id);
        if(music==null){
            return new Result(-1,"数据库中没有你要删的音乐",false);
        }
        String title = music.getTitle();
        String path = SAVE_PATH + "\\"+title+".mp3";
        log.info("删除的歌曲 path  = "+ path);
        File dest = new File(path);
        dest.delete();
        //删数据库
        int ret = musicMapper.deleteMusic(id);
        loveMusicMapper.deleteLoveMusic(id,music.getUserId());
        if(ret==0){
            //删除失败
            log.info("数据库删除失败");
            return new Result(-1,"数据库删除失败",false);
        }else {
            //成功
            log.info("数据库删除成功");
        }
        return new Result(200,"音乐删除成功",true);
    }

    @RequestMapping("/batchDelete")
    public Result batchDelete(@RequestParam List<Integer> ids){
        //TODO批量删除
        for (Integer id:ids) {
            Music music = musicMapper.selectById(id);
            String title = music.getTitle();
            String path = SAVE_PATH + "\\"+title+".mp3";
            log.info("删除的歌曲 path  = "+ path);
            File dest = new File(path);
            dest.delete();
        }
        int ret = musicMapper.batchDelete(ids);
        System.out.println(ids.toString());
        if ((ret>=0)){
            return new Result(200,"成功",true);
        } else {
            return new Result(-1,"成批",false);
        }
    }
    // 查询音乐
    @RequestMapping("/findmusic")//(required=false)可以不传⼊参数
    public Result findMusic(@RequestParam(required=false)
                                                      String musicName) {
        List<Music> musicList = null;
        if(musicName != null) {
            musicList = musicMapper.findMusicByMusicName(musicName);
        }else {
//默认查询全部的⾳乐
            musicList = musicMapper.findMusic();
        }
        return new Result(200,"查询到了歌曲的信息",musicList);
    }


}
